# @Author: 唐奇才
# @Time: 2021/6/8 14:31
# @File: 9.基于SVM分析UCI银行营销数据集.py
# @Software: PyCharm

# 导入所依赖的包
# 包括数据处理 pandas 以及 机器学习 sklearn
import pandas as pd
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder

# 为了计算速度更快 使用小数据集
# 用pandas包加载csv数据集
data = pd.read_csv('./data/bank-additional.csv', sep=';')


# 对于object类型值 用labelencoder编码
# attr 为要编码的属性
attr = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome', 'y']
for i in attr:
    le = LabelEncoder()
    le.fit(data[i])
    t = le.transform(data[i])
    print(t, len(t))
    data[i] = t



# 取得输入集x 以及输出集y
# 并划分训练集与测试集 (7:3)
x = data[['age', 'job', 'marital', 'education', 'default',
          'housing', 'loan', 'contact', 'month', 'day_of_week',
          'duration', 'campaign', 'pdays', 'previous', 'poutcome',
          'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m', 'nr.employed']].values
y = data['y'].values
x_tr, x_te, y_tr, y_te = train_test_split(x, y, test_size=0.3, random_state=0)


# 训练并测试
svc = SVC(C=2, kernel='rbf', decision_function_shape='ovo')
svc.fit(x_tr, y_tr)
print("\nsvm accuracy is: ", svc.score(x_te, y_te))

